﻿using System;
using System.Net.Mail;
using System.IO;

namespace DotNetNexusSpam.SpamFilter
{
    class BlackListFilter : FilterBase
    {
        public BlackListFilter(CDOMessageWrapper email, string startupPath)
            : base(email, startupPath)
        {
            base.Name = "Blacklist";
        }

        public override void Fire()
        {
            base.ActionToTake = FilterAction.PROCESS_NORMALLY;
            base.IsSpam = false;

            if (_blacklist.Length > 0)
            {
                foreach (string s in _blacklist)
                {
                    if (Email.CDOMessage.From.Contains(s))
                    {
                        ActionToTake = FilterAction.DELETE_EMAIL;
                        IsSpam = true;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Load all words that the engine uses to (definitively) delete spam.
        /// </summary>
        private const string BLACK_LIST = "blacklist.txt";
        private string[] _blacklist;
        public override void LoadConfiguration()
        {
            string settingsPath = base.StartupPath + "config\\" + BLACK_LIST;
            if (File.Exists(settingsPath))
            {
                string blackListContent = "";
                using (StreamReader settingsReader = new StreamReader(settingsPath))
                {
                    blackListContent = settingsReader.ReadToEnd();
                }
                _blacklist = blackListContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                _log.Debug("Blacklist file was loaded succesfully.");
            }
            else
            {
                _log.Warn("Blacklist file could not be loaded from " + settingsPath);
            }
        }
    }
}
